<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="网络编程,">





  <link rel="alternate" href="/blogs/atom.xml" title="恋恋风辰的个人博客" type="application/atom+xml">






<meta name="description" content="之前梳理过redis main函数主体流程 `大体是 initServerConfig() -&amp;gt; loadServerConfig() -&amp;gt; daemonize() -&amp;gt; initServer() -&amp;gt; aeSetBeforeSleepProc() -&amp;gt;aeMain() -&amp;gt; aeDeleteEventLoop(); initServerConfig() 初始化">
<meta name="keywords" content="网络编程">
<meta property="og:type" content="article">
<meta property="og:title" content="对于redis框架的理解（二）">
<meta property="og:url" content="https://secondtonone1.gitee.io/blogs/2017/08/07/redis2/index.html">
<meta property="og:site_name" content="恋恋风辰的个人博客">
<meta property="og:description" content="之前梳理过redis main函数主体流程 `大体是 initServerConfig() -&amp;gt; loadServerConfig() -&amp;gt; daemonize() -&amp;gt; initServer() -&amp;gt; aeSetBeforeSleepProc() -&amp;gt;aeMain() -&amp;gt; aeDeleteEventLoop(); initServerConfig() 初始化">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-06-22T09:30:59.100Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="对于redis框架的理解（二）">
<meta name="twitter:description" content="之前梳理过redis main函数主体流程 `大体是 initServerConfig() -&amp;gt; loadServerConfig() -&amp;gt; daemonize() -&amp;gt; initServer() -&amp;gt; aeSetBeforeSleepProc() -&amp;gt;aeMain() -&amp;gt; aeDeleteEventLoop(); initServerConfig() 初始化">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blogs/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://secondtonone1.gitee.io/blogs/2017/08/07/redis2/">





  <title>对于redis框架的理解（二） | 恋恋风辰的个人博客</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">恋恋风辰的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blogs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blogs/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://secondtonone1.gitee.io/blogs/blogs/2017/08/07/redis2/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="恋恋风辰">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="恋恋风辰的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">对于redis框架的理解（二）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-08-07T16:22:07+08:00">
                2017-08-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/blogs/categories/netprogram/" itemprop="url" rel="index">
                    <span itemprop="name">网络编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>之前梳理过<code>redis</code> main函数主体流程</p>
<p>`大体是 initServerConfig() -&gt; loadServerConfig()</p>
<p><code>-&gt; daemonize() -&gt; initServer() -&gt; aeSetBeforeSleepProc()</code></p>
<p><code>-&gt;aeMain() -&gt; aeDeleteEventLoop();</code></p>
<p><code>initServerConfig()</code> 初始化server的配置</p>
<p><code>loadServerConfig()</code>会从配置文件里加载对应的配置</p>
<p><code>daemonize()</code>创建守护进程</p>
<p>看一下daemonize的函数组成<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">daemonize</span><span class="params">(<span class="keyword">void</span>)</span> </span>&#123;</span><br><span class="line">　　<span class="keyword">int</span> fd;</span><br><span class="line"></span><br><span class="line">　　<span class="keyword">if</span> (fork() != <span class="number">0</span>) <span class="built_in">exit</span>(<span class="number">0</span>); <span class="comment">/* parent exits */</span></span><br><span class="line">　　<span class="comment">//设置为首进程</span></span><br><span class="line">　　<span class="comment">//之前parent和child运行在同一个session里,</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">//parent是会话（session）的领头进程,</span></span><br><span class="line">　　<span class="comment">//parent进程作为会话的领头进程，如果exit结束执行的话，</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">//那么子进程会成为孤儿进程，并被init收养。</span></span><br><span class="line">　　<span class="comment">//执行setsid()之后,child将重新获得一个新的会话(session)id。</span></span><br><span class="line">　　setsid(); <span class="comment">/* create a new session */</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">/* Every output goes to /dev/null. If Redis is daemonized but</span></span><br><span class="line"><span class="comment">　　* the 'logfile' is set to 'stdout' in the configuration file</span></span><br><span class="line"><span class="comment">　　* it will not log at all. */</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">//  /dev/null相当于黑洞文件，所有写入他的数据都会消失，</span></span><br><span class="line"></span><br><span class="line">　　<span class="comment">//从他里面读不出数据</span></span><br><span class="line">　　<span class="keyword">if</span> ((fd = open(<span class="string">"/dev/null"</span>, O_RDWR, <span class="number">0</span>)) != <span class="number">-1</span>) &#123;</span><br><span class="line">　　　　dup2(fd, STDIN_FILENO);    <span class="comment">//将标准输入重定向到fd</span></span><br><span class="line">　　　　dup2(fd, STDOUT_FILENO); <span class="comment">//将标准输出重定向到fd</span></span><br><span class="line">　　　　dup2(fd, STDERR_FILENO); <span class="comment">//将错误输出重定向到fd</span></span><br><span class="line">　　　　<span class="keyword">if</span> (fd &gt; STDERR_FILENO)</span><br><span class="line"></span><br><span class="line">　　　　　　close(fd);</span><br><span class="line"></span><br><span class="line">　　　&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a> 
<p>着重解释下<code>dup2</code>这个函数</p>
<p><code>int dup(int oldfd);</code></p>
<p>复制oldfd所指向的文件描述符，返回系统目前未使用的最小的文件描述符。</p>
<p>新的文件描述符和oldfd指向一个文件，</p>
<p>他们<code>共享读写，枷锁等权限</code>，<code>当一个文件描述符操作lseek，另一个也会随着偏移</code>。</p>
<p>但是他们<code>不共享close-on-exec</code>。</p>
<p><code>int dup2(int oldfd, int newfd);</code></p>
<p><code>复制oldfd到newfd，如果newfd指向的文件打开，那么会关闭该文件。</code></p>
<p><code>dup2失败后返回-1，成功则共享文件状态。</code></p>
<p>接下来看看initServer函数做了些什么 下面是initServer内部的几个步骤</p>
<p>//由于initserver是守护进程，忽略sighup<br>//sighub在控制终端关闭的时候会发给session首进程<br>//session首进程退出时，该信号被发送到该session中的前台进程组中的每一个进程<br><code>signal(SIGHUP, SIG_IGN);</code></p>
<p>//写管道发现读进程终止时产生sigpipe信号，</p>
<p>//写已终止的SOCK_STREAM套接字同样会产生此信号<br><code>signal(SIGPIPE, SIG_IGN);</code><br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">server.pid = getpid();</span><br><span class="line">server.current_client = <span class="literal">NULL</span>;</span><br><span class="line">server.clients = listCreate(); <span class="comment">//创建客户队列</span></span><br><span class="line">server.clients_to_close = listCreate(); <span class="comment">//创建关闭队列</span></span><br><span class="line">server.slaves = listCreate(); <span class="comment">//创建从机队列</span></span><br><span class="line">server.monitors = listCreate(); <span class="comment">//创建监控队列</span></span><br><span class="line">server.slaveseldb = <span class="number">-1</span>; <span class="comment">/* Force to emit the first SELECT command. */</span></span><br><span class="line">server.unblocked_clients = listCreate(); <span class="comment">//创建非堵塞客户队列</span></span><br><span class="line">server.ready_keys = listCreate(); <span class="comment">//创建可读键队列</span></span><br><span class="line">server.clients_waiting_acks = listCreate(); <span class="comment">//客户等待回包队列</span></span><br><span class="line">server.get_ack_from_slaves = <span class="number">0</span>;</span><br><span class="line">server.clients_paused = <span class="number">0</span>;</span><br></pre></td></tr></table></figure></p>
<p>//创建别的模块公用的对象<br><code>createSharedObjects(); //创建共享对象</code><br><code>adjustOpenFilesLimit(); //改变可打开文件的最大数量</code></p>
<p>可以看看<code>adjustOpenFilesLimit()</code>里边做了什么<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">adjustOpenFilesLimit</span><span class="params">(<span class="keyword">void</span>)</span> </span>&#123;</span><br><span class="line">　　　　<span class="keyword">rlim_t</span> maxfiles = server.maxclients+REDIS_MIN_RESERVED_FDS;</span><br><span class="line">　　　　<span class="class"><span class="keyword">struct</span> <span class="title">rlimit</span> <span class="title">limit</span>;</span></span><br><span class="line"></span><br><span class="line">　　　　<span class="comment">//获取每个进程能创建的各种系统资源的最大数量</span></span><br><span class="line">　　　　<span class="keyword">if</span> (getrlimit(RLIMIT_NOFILE,&amp;limit) == <span class="number">-1</span>) &#123;</span><br><span class="line">　　　　redisLog(REDIS_WARNING,<span class="string">"Unable to obtain the current NOFILE limit (%s),</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">　　　　assuming 1024 and setting the max clients configuration accordingly."</span>,</span><br><span class="line">　　　　strerror(errno));</span><br><span class="line">　　　　<span class="comment">//1024 - 目前redis最小保留的用于其他功能的描述符</span></span><br><span class="line">　　　　server.maxclients = <span class="number">1024</span>-REDIS_MIN_RESERVED_FDS;</span><br><span class="line">　　　　&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">　　　　　　　　<span class="comment">//系统当前（软）限制</span></span><br><span class="line">　　　　　　　　<span class="keyword">rlim_t</span> oldlimit = limit.rlim_cur;</span><br><span class="line"></span><br><span class="line">　　　　　　　　<span class="comment">/* Set the max number of files if the current limit is not enough</span></span><br><span class="line"><span class="comment">　　　　　　　　* for our needs. */</span></span><br><span class="line">　　　　　　　　<span class="keyword">if</span> (oldlimit &lt; maxfiles) &#123;</span><br><span class="line">　　　　　　　　<span class="comment">//最大软件限制</span></span><br><span class="line">　　　　　　　　<span class="keyword">rlim_t</span> bestlimit;</span><br><span class="line">　　　　　　　　<span class="keyword">int</span> setrlimit_error = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">　　　　　　　　<span class="comment">/* Try to set the file limit to match 'maxfiles' or at least</span></span><br><span class="line"><span class="comment">　　　　　　　　* to the higher value supported less than maxfiles. */</span></span><br><span class="line">　　　　　　　　<span class="comment">//尝试设置限制数符合maxfiles或者最接近</span></span><br><span class="line">　　　　　　　　bestlimit = maxfiles;</span><br><span class="line">　　　　　　　　<span class="comment">//循环判断，如果最大的连接数大于当前系统能使用的最大软件限制</span></span><br><span class="line">　　　　　　　　<span class="keyword">while</span>(bestlimit &gt; oldlimit) &#123;</span><br><span class="line">　　　　　　　　<span class="comment">//设置每次递减的数量</span></span><br><span class="line">　　　　　　　　<span class="keyword">rlim_t</span> decr_step = <span class="number">16</span>;</span><br><span class="line">　　　　　　　　<span class="comment">//设置当前软件限制</span></span><br><span class="line">　　　　　　　　limit.rlim_cur = bestlimit;</span><br><span class="line">　　　　　　　　limit.rlim_max = bestlimit;</span><br><span class="line">　　　　　　　　<span class="comment">//设置成功则断开，不成功继续循环，找到最接近的最大限制</span></span><br><span class="line">　　　　　　　　<span class="keyword">if</span> (setrlimit(RLIMIT_NOFILE,&amp;limit) != <span class="number">-1</span>) <span class="keyword">break</span>;</span><br><span class="line">　　　　　　　　<span class="comment">//设置限制错误码</span></span><br><span class="line">　　　　　　　　setrlimit_error = errno;</span><br><span class="line"></span><br><span class="line">　　　　　　　　<span class="comment">/* We failed to set file limit to 'bestlimit'. Try with a</span></span><br><span class="line"><span class="comment">　　　　　　　　* smaller limit decrementing by a few FDs per iteration. */</span></span><br><span class="line"></span><br><span class="line">　　　　　　　　<span class="comment">//最大限制递减，如果小于规定值那么退出循环</span></span><br><span class="line">　　　　　　　　<span class="keyword">if</span> (bestlimit &lt; decr_step) <span class="keyword">break</span>;</span><br><span class="line">　　　　　　　　bestlimit -= decr_step;</span><br><span class="line">　　　　　　　　　　　　<span class="comment">/* Assume that the limit we get initially is still valid if</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">　　　　　　* our last try was even lower. */</span></span><br><span class="line">　　　　　　<span class="comment">//最大连接数小于当前系统允许的资源数量，那么扩充为系统允许的数量</span></span><br><span class="line">　　　　　　<span class="keyword">if</span> (bestlimit &lt; oldlimit) bestlimit = oldlimit;</span><br><span class="line"></span><br><span class="line">　　　　　　<span class="comment">//这个条件用于处理最大连接数</span></span><br><span class="line">　　　　　　<span class="keyword">if</span> (bestlimit &lt; maxfiles) &#123;</span><br><span class="line">　　　　　　<span class="comment">//保存当前服务器客户队列最大数量</span></span><br><span class="line">　　　　　　　　<span class="keyword">int</span> old_maxclients = server.maxclients;</span><br><span class="line">　　　　　　　　<span class="comment">//服务器客户队列最大数量</span></span><br><span class="line">　　　　　　　　server.maxclients = bestlimit-REDIS_MIN_RESERVED_FDS;</span><br><span class="line">　　　　　　　　<span class="keyword">if</span> (server.maxclients &lt; <span class="number">1</span>) &#123;</span><br><span class="line">　　　　　　　　　　redisLog(REDIS_WARNING,<span class="string">"Your current 'ulimit -n' "</span></span><br><span class="line">　　　　　　　　　　<span class="string">"of %llu is not enough for Redis to start. "</span></span><br><span class="line">　　　　　　　　　　<span class="string">"Please increase your open file limit to at least "</span></span><br><span class="line">　　　　　　　　　　<span class="string">"%llu. Exiting."</span>,</span><br><span class="line">　　　　　　　　　　(<span class="keyword">unsigned</span> <span class="keyword">long</span> <span class="keyword">long</span>) oldlimit,</span><br><span class="line">　　　　　　　　　　(<span class="keyword">unsigned</span> <span class="keyword">long</span> <span class="keyword">long</span>) maxfiles);</span><br><span class="line">　　　　　　　　　　<span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">　　　　　　　　&#125;</span><br><span class="line"></span><br><span class="line">　　　&#125;</span><br></pre></td></tr></table></figure></p>
<p>回到initServer函数内部</p>
<p>adjustOpenFilesLimit()函数过后是调用</p>
<p><code>server.el = aeCreateEventLoop(server.maxclients+REDIS_EVENTLOOP_FDSET_INCR);</code></p>
<p>这个函数是创建基本的时间循环结构。这个api写在Ae.c中，这个文件主要负责创建事件轮询的结构，创建文件读写事件，删除文件读写事件，删除事件轮询结构，派发文件读写功能等，下一节再讲。</p>
<p>然后是创建了一个定时器回调函数</p>
<p><code>if(aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) {
redisPanic(&quot;Can&#39;t create the serverCron time event.&quot;);
exit(1);
}</code></p>
<p>接着创建了 TCP的回调函数，主要用于有新的连接到来触发acceptTcpHandler</p>
<p><code>for (j = 0; j &lt; server.ipfd_count; j++) {
if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE,
    acceptTcpHandler,NULL) == AE_ERR)
    {
    redisPanic(
    &quot;Unrecoverable error creating server.ipfd file event.&quot;);
    }
}</code></p>
<p>//然后添加了udp的回调<br><code>if (server.sofd &gt; 0 &amp;&amp; aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
acceptUnixHandler,NULL) == AE_ERR) redisPanic(&quot;Unrecoverable error creating server.sofd file event.&quot;);</code></p>
<p>这就是initServer大体的流程</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/网络编程/" rel="tag"># 网络编程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2017/08/07/redis4/" rel="next" title="对于redis框架的理解（四）">
                <i class="fa fa-chevron-left"></i> 对于redis框架的理解（四）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2017/08/07/redis3/" rel="prev" title="对于redis框架的理解(三)">
                对于redis框架的理解(三) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">恋恋风辰</p>
              <p class="site-description motion-element" itemprop="description">重剑无锋，大巧不工</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives/">
              
                  <span class="site-state-item-count">146</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blogs/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blogs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/secondtonone1" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/wang-wu-chen-32/activities" target="_blank" title="ZhiHu">
                    
                      <i class="fa fa-fw fa-ZhiHu"></i>ZhiHu</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">恋恋风辰</span>

  
  
 
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
 
 
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.3</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blogs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
